package config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Configuration
public class RedisConfig {
	
	@Value("0")
	private int cacheRedisDbId;
	
	@Value("1")
	private int lockRedisDbId;

	@Autowired
	JedisConnectionFactory cacheJedisConnectionFactory;
	
	@Autowired
	JedisConnectionFactory lockJedisConnectionFactory;
	
	@Bean(name="cacheRedisTemplate")
	public RedisTemplate<Object, Object> cacheRedisTemplate(){
		final RedisTemplate<Object,Object> template = new RedisTemplate<>();
		cacheJedisConnectionFactory.setDatabase(cacheRedisDbId);
	    template.setConnectionFactory(cacheJedisConnectionFactory);
	    template.setKeySerializer(new StringRedisSerializer());
	    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
	    template.setHashKeySerializer(new StringRedisSerializer());
	    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
		return template;
	}
	
	@Bean(name="lockRedisTemplate")
	public RedisTemplate<Object, Object> lockRedisTemplate(){
		final RedisTemplate<Object,Object> template = new RedisTemplate<>();
		lockJedisConnectionFactory.setDatabase(lockRedisDbId);
	    template.setConnectionFactory(lockJedisConnectionFactory);
	    template.setKeySerializer(new StringRedisSerializer());
	    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
	    template.setHashKeySerializer(new StringRedisSerializer());
	    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
		return template;
	}
}
